import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, DatePicker, Divider, Drawer, Form, Input, InputNumber, message, Modal, Select, Tag} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import OrderApplyForm from './components/OrderApplyForm';
import {addOrder, deductOrder, finishOrder, queryOrder, refundOrder, removeOrder, updateOrder} from "@/services/order";
import moment from "moment";


const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [refundModalVisible, setRefundModalVisible] = useState(false);
  const [deductModalVisible, setDeductModalVisible] = useState(false);
  const [formType, setFormType] = useState(1) // 1:新增 2:更新 3：详情
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [refundForm] = Form.useForm();
  const [deductForm] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRow, setSelectedRow] = useState({});
  const {Option} = Select;
  const {RangePicker} = DatePicker;
  const handleUpdateModalVisible = (record) => {
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    handleModalVisible(true)
    setFormType(2)
  }
  const handleRefundModalVisible = (record) => {
    refundForm.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    setRefundModalVisible(true)
  }
  const handleDeductModalVisible = (record) => {
    deductForm.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    setDeductModalVisible(true)
  }

  const handleCreateModalVisible = () => {
    handleModalVisible(true)
    setFormType(1)
  }

  const handleDetailModalVisible = (record) => {
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    handleModalVisible(true)
    setFormType(3)
  }

  const handleAdd = async (fields) => {
    //console.log(('handleAdd')
    const hide = message.loading('正在添加');

    try {
      await addOrder({...fields}).then(res => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success('添加成功');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
        }
      });
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const handleUpdate = async (fields) => {
    const hide = message.loading('正在配置');

    try {
      await updateOrder({...fields}).then(res => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success('配置成功');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
        }
      });
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeOrder({
        ...selectedRows
      }).then(res => {
        if (res && res.status === '0') {
          hide();
          message.success('删除成功，即将刷新');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
        }
      });

      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const handleFinish = (record) => {
    try {
      finishOrder({
        ...record
      }).then(res => {
        if (res && res.status === '0') {
          message.success('订单已完结，即将刷新');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
        }
      });

      return true;
    } catch (error) {
      message.error('完结失败，请重试');
    }
  }

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除订单编码为 【${record.orderCode} 】的订单？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        const success = handleRemove(record)
        // if (success && actionRef.current) {
        //   actionRef.current.reload();
        // }
      }
    });
  };

  const orderFinishConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `确认完成订单 【${record.orderCode} 】？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        handleFinish(record)
      }
    });
  }

  const onSubmit = (orderDatas) => {
    let success;
    if (formType === 1) {
      success = handleAdd(orderDatas);
    } else {
      orderDatas.orderId = selectedRow.orderId;
      success = handleUpdate(orderDatas)
    }
    // if (success && actionRef.current) {
    //   actionRef.current.reload();
    // }
  }

  const handleRefundSubmit = () => {
    refundForm.validateFields().then(values => {
      refundOrder({
        orderCode: values.orderCode,
        chargebackNum: values.chargebackNumNew,
        orderId: selectedRow.orderId
      }).then(res => {
        if (res && res.status === '0') {
          message.success("退单成功")
          setRefundModalVisible(false)
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message)
        }
      })
    })
  }

  const handleDeductSubmit = () => {
    deductForm.validateFields().then(values => {
      deductOrder({
        orderCode: values.orderCode,
        deductByCust: values.deductByCustNew,
        orderId: selectedRow.orderId
      }).then(res => {
        if (res && res.status === '0') {
          message.success("更新扣款金额成功")
          setDeductModalVisible(false)
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message)
        }
      })
    })
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      width: 100,
      fixed: 'left',
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      tip: '订单编号是唯一的',
      fixed: 'left',
      width: 200,
      hideInForm: true,
      copyable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入订单编号'}/>;
      }
    },
    // {
    //   title: '产品名称',
    //   dataIndex: 'productName',
    //   fixed: 'left',
    //   width: 150,
    //   formItemProps: {
    //     rules: [
    //       {
    //         max: 10,
    //         message: '产品名称最大长度为10'
    //       },
    //       {
    //         whitespace: true,
    //         message: '请不要输入空格'
    //       }
    //     ],
    //   },
    //   valueType: 'input',
    //   renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
    //     return <Input maxLength={11} {...fieldProps} placeholder={'请输入产品名称'}/>;
    //   }
    // },
    {
      title: '产品编码',
      dataIndex: 'productCode',
      fixed: 'left',
      width: 150,
    },
    {
      title: '生产编号',
      dataIndex: 'productionNo',
      fixed: 'left',
      width: 150,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} placeholder={'请输入生产编号'}/>;
      }
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      sorter: true,
      width: 150,
      hideInForm: true,
      render: (text) => {
        return (
          <Tag>{text === 0 ? '草稿' :
            text === 1 ? '待审批' :
              text === 2 ? '审批驳回' :
                text === 3 ? '工程评审中' :
                  text === 4 ? '工程评审驳回' :
                    text === 5 ? '生产评审中' :
                      text === 6 ? '生产审批驳回' :
                        text === 7 ? '工程作业中' :
                          text === 8 ? '生产作业中' :
                            text === 9 ? '投产中' :
                              text === 10 ? '出库中' : '已完结'
          }</Tag>
        )
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={-1}>全部</Option>
            <Option value={0}>草稿</Option>
            <Option value={1}>待审批</Option>
            <Option value={2}>审批驳回</Option>
            <Option value={3}>工程评审中</Option>
            <Option value={4}>工程评审驳回</Option>
            <Option value={5}>生产评审中</Option>
            <Option value={6}>生产审批驳回</Option>
            <Option value={7}>工程作业中</Option>
            <Option value={8}>生产作业中</Option>
            <Option value={9}>投产中</Option>
            <Option value={10}>出库中</Option>
            <Option value={11}>已完结</Option>
          </Select>
        );
      }
    },
    {
      title: '客户名称',
      dataIndex: 'custName',
      width: 150,
    },
    {
      title: '客户型号',
      dataIndex: 'clientCode',
      hideInSearch: true,
      hideInTable: true,
      width: 150,
    },
    {
      title: '订货量(PCS)',
      dataIndex: 'orderNum',
      width: 150,
      hideInSearch: true
    },
    {
      title: '订单金额(元)',
      width: 150,
      dataIndex: 'orderPrice',
      hideInSearch: true
    },
    {
      title: '客户扣款金额(元)',
      dataIndex: 'deductByCust',
      width: 200,
      hideInSearch: true
    },
    {
      title: '计划投产量',
      dataIndex: 'productionNum',
      width: 200,
      hideInSearch: true
    },
    {
      title: '预投率',
      dataIndex: 'planForProductionRatio',
      width: 150,
      hideInSearch: true,
      render: (text, record) => {
        return record.productionNum ? ((record.productionNum - record.orderNum) * 100 / record.orderNum).toFixed(2) + '%' : null
      }
    },
    {
      title: '备品数',
      dataIndex: 'marginNum',
      width: 150,
      hideInSearch: true
    },
    {
      title: '厂内报废数量',
      dataIndex: 'scrapNum',
      width: 150,
      hideInSearch: true
    },
    {
      title: '厂外报废数量',
      dataIndex: 'cstScrapNum',
      width: 150,
      hideInSearch: true
    },
    {
      title: '已出货数量',
      dataIndex: 'shippedNum',
      width: 200,
      hideInSearch: true
    },
    {
      title: '退货返修数',
      dataIndex: 'chargebackNum',
      width: 150,
      hideInSearch: true
    },
    {
      title: '退单入库数量',
      dataIndex: 'salesReturnStockIn',
      width: 200,
      hideInSearch: true
    },
    {
      title: '累计需补数',
      dataIndex: 'toBeSuppliedNum',
      width: 150,
      hideInSearch: true
    },
    {
      title: '余数量',
      dataIndex: 'remainNum',
      width: 150,
      hideInSearch: true
    },
    {
      title: '订单创建人',
      dataIndex: 'realName',
      width: 200,
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      sorter: true,
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <RangePicker showTime/>
        );
      }
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 300,
      fixed: 'right',
      render: (_, record) => {
        switch (record.orderStatus) {
          case 0:
            return [
              <a onClick={() => handleDetailModalVisible(record)}>
                详情
              </a>,
              <Divider type="vertical"/>,
              <a
                onClick={() => handleUpdateModalVisible(record)}>修改</a>,
              <Divider type="vertical"/>,
              <a onClick={() => deleteConfig(record)}>删除</a>,
            ];
          case 9:
            return [
              <a onClick={() => handleDetailModalVisible(record)}>
                详情
              </a>,
              // <Divider
              //   type="vertical"/>,
              // <a
              //   onClick={() => handleRefundModalVisible(record)}>退单</a>,
              // <Divider
              //   type="vertical"/>,
              // <a
              //   onClick={() => handleDeductModalVisible(record)}>扣款</a>,
            ];
          case 10:
            return [
              <a onClick={() => handleDetailModalVisible(record)}>
                详情
              </a>,
              // <Divider
              //   type="vertical"/>,
              // <a
              //   onClick={() => handleRefundModalVisible(record)}>退单</a>,
              <Divider type="vertical"/>,
              <a
                onClick={() => orderFinishConfig(record)}>订单完结</a>,
              // <Divider
              //   type="vertical"/>,
              // <a
              //   onClick={() => handleDeductModalVisible(record)}>扣款</a>,
            ];
          default:
            return [<a onClick={() => handleDetailModalVisible(record)}>
              详情
            </a>]
        }

        // return [
        //   <a onClick={() => handleDetailModalVisible(record)}>
        //     详情
        //   </a>,
        //   <Divider style={{display: record.orderStatus === 0 ? '' : 'none'}} type="vertical"/>,
        //   <a style={{display: record.orderStatus === 0 ? '' : 'none'}}
        //      onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        //   <Divider style={{display: record.orderStatus === 0 ? '' : 'none'}} type="vertical"/>,
        //   <a style={{display: record.orderStatus === 0 ? '' : 'none'}} onClick={() => deleteConfig(record)}>删除</a>,
        //   <Divider style={{display: record.orderStatus === 9 || record.orderStatus === 10 ? '' : 'none'}}
        //            type="vertical"/>,
        //   <a style={{display: record.orderStatus === 9 || record.orderStatus === 10 ? 'block' : 'none'}}
        //      onClick={() => handleRefundModalVisible(record)}>退单</a>,
        //   <Divider style={{display: record.orderStatus === 10 ? '' : 'none'}} type="vertical"/>,
        //   <a style={{display: record.orderStatus === 10 ? '' : 'none'}}
        //      onClick={() => orderFinishConfig(record)}>订单完结</a>,
        //   <Divider style={{display: record.orderStatus === 9 || record.orderStatus === 10 ? '' : 'none'}}
        //            type="vertical"/>,
        //   <a style={{display: record.orderStatus === 9 || record.orderStatus === 10 ? 'block' : 'none'}}
        //      onClick={() => handleDeductModalVisible(record)}>扣款</a>,
        // ]
      }
    },
  ];
  const tableRef = useRef();
  return (
    <PageContainer>
      <ProTable
        style={{display: createModalVisible ? 'none' : 'block'}}
        actionRef={actionRef}
        formRef={tableRef}
        rowKey="orderId"
        sticky
        scroll={{x: 2700}}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {
            ...params,
            pageNum: params.current,
            // createBy: JSON.parse(sessionStorage.getItem('user')).sysUser.userId
          };
          const res = await queryOrder(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
      />
      {
        createModalVisible ? <OrderApplyForm
          onCancel={() => handleModalVisible(false)}
          visible={createModalVisible}
          onSubmit={(orderData) => onSubmit(orderData)}
          formType={formType}
          oldOrderData={selectedRow}
        >
        </OrderApplyForm> : <></>
      }
      <Modal
        destroyOnClose
        title={'退单'}
        width={800}
        visible={refundModalVisible}
        onCancel={() => setRefundModalVisible(false)}
        wrapClassName={'normalModal'}
        onOk={() => handleRefundSubmit()}
      >
        <Form form={refundForm} name="transferForm">
          <Form.Item name="orderCode" label="订单编号">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="custName" label="客户">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="orderNum" label="订单数量">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="chargebackNumNew" label="本次退单数量" rules={[
            {
              pattern: /^[1-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={1}/>
          </Form.Item>
          <Form.Item name="chargebackNum" label="累计退单数量">
            <Input disabled={true}/>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        destroyOnClose
        title={'客户扣款金额'}
        width={800}
        visible={deductModalVisible}
        onCancel={() => setDeductModalVisible(false)}
        wrapClassName={'normalModal'}
        onOk={() => handleDeductSubmit()}
      >
        <Form form={deductForm} name="transferForm">
          <Form.Item name="orderCode" label="订单编号">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="custName" label="客户">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="orderNum" label="订单数量">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="deductByCustNew" label="本次扣款金额(元)" rules={[
            {
              pattern: /^\d+(\.\d{0,2})?$/,
              message: '只能输入两位小数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={1}/>
          </Form.Item>
          <Form.Item name="deductByCust" label="累计扣款金额(元)">
            <Input disabled={true}/>
          </Form.Item>
        </Form>
      </Modal>
      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.orderId && (
          <ProDescriptions
            column={2}
            title={row?.orderId}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.orderId,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
